using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PP.Basic;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

namespace PP.PPPoker.Game.GJ25
{
    /// <summary>
    /// GJ25LeaderBoard 对象
    /// </summary>
    public class GJ25LeaderBoard : MonoBehaviour
    {
        private const string Tag = nameof(GJ25LeaderBoard);

        // Private Variables Begin
        public class LeaderboardEntry
        {
            public string name;
            public int score;
            public string time;

            public LeaderboardEntry(string name, int score, string time)
            {
                this.name = name;
                this.score = score;
                this.time = time;
            }
        }

        private List<LeaderboardEntry> _dataList = new();


        // Private Variables End

        // Static Methods Begin
        public static GJ25LeaderBoard Create()
        {
            return UIManager.Instance.ShowView<GJ25LeaderBoard>("Prefab/GJ25LeaderBoard");
        }
        // Static Methods End

        // Public Methods Begin
        // Public Methods End

        // 结束请求
        private IEnumerator HttpReqLeaderBoard()
        {
            var url = $"{GameConfig.ServerDomain}/api/get_leaderboard";

            Debug.Log($"{Tag}.# HttpReqType -> url: {url}");

            UnityWebRequest www = UnityWebRequest.Get(url);
            yield return www.SendWebRequest();
            if (www.result == UnityWebRequest.Result.Success)
            {
                var jsRet = JObject.Parse(www.downloadHandler.text);
                if (jsRet == null)
                {
                    Debug.LogWarning($"{Tag}.pop.check -> result = null ");
                    yield return null;
                }
                int code = (int)jsRet["code"]?.Value<int>();

                JArray dataArray = (JArray)jsRet["data"];
                if (dataArray == null)
                {
                    Debug.LogWarning($"{Tag}.pop.check -> dataArray = null ");
                    yield return null;
                }

                // 3. 遍历或转 List<Dictionary<string, object>>
                foreach (JObject item in dataArray)
                {
                    string name = item["name"].ToString();
                    int score = item["score"].ToObject<int>();
                    string time = item["time"].ToString();

                    Debug.Log($"Name: {name}, Score: {score}, Time: {time}");

                    _dataList.Add(new LeaderboardEntry(name, score, time));
                }

                ShowData();

            }
        }


        private void ShowData()
        {
            for (int i = 0; i < _dataList.Count; i++)
            {
                var item = _dataList[i];
                Debug.Log($"Name: {item.name}, Score: {item.score}, Time: {item.time}");
                var gJ25LeaderItem = GJ25LeaderItem.Create(_scrollContentTrans);
                //gJ25LeaderItem.transform.SetParent(_scrollContentTrans, false);
                gJ25LeaderItem.gameObject.SetActive(true);
                gJ25LeaderItem.SetItem(i+1, item.name, item.score, item.time);
            }

        }


        // Lifecycle Methods Begin
        protected void Awake()
        {
            InitHier();
            InitPart();
        }

        private void InitPart()
        {
            // Do initialization here...
        }

        private void Start()
        {
            Debug.Log($"{Tag}.Start");

            StartCoroutine( HttpReqLeaderBoard());
        }

        // Lifecycle Methods End


        // Hier Components Begin        
        private Image _backgroundImage;
        private GJ25LeaderItem _gJ25LeaderItem;
        private Transform _scrollContentTrans;
        private Button _reTryButton;

        private void InitHier()
        {
            _backgroundImage = transform.Find("_Image_Background").GetComponent<Image>();
            _gJ25LeaderItem = transform.Find("_Image_Background/Scroll View/_GJ25LeaderItem#").GetComponentEx<GJ25LeaderItem>();
            //_gJ25LeaderItem.Initiate();
            _scrollContentTrans = transform.Find("_Image_Background/Scroll View/Viewport/_Trans_ScrollContent");
            _reTryButton = transform.Find("_Button_ReTry").GetComponent<Button>();
            _reTryButton.onClick.AddListener(OnReTryButtonClick);
        }


        private void OnReTryButtonClick()
        {
            //Dispose();

            //Destroy(gameObject);
            UIManager.Instance.CloseView<GJ25LeaderBoard>();
            UIManager.Instance.CloseView<GJEndingLayer>();
            UIManager.Instance.CloseView<GJRuleLayer>();
            GJ25Layer.Create();
        }
        // Hier Components End
    }




    // *************************************************





    public class GJ25LeaderItem : MonoBehaviour
    {
        private const string Tag = nameof(GJ25LeaderItem);

        // Private Variables Begin
        // Private Variables End

        // Static Methods Begin
        public static GJ25LeaderItem Create(Transform transform)
        {
            return UIUtil.Create<GJ25LeaderItem>("Prefab/GJ25LeaderItem", transform);
        }
        // Static Methods End

        // Public Methods Begin

        public void SetItem(int rank, string name, int score, string time)
        {
            _rankTextTmp.text = rank.ToString();
            _nameTextTmp.text = name;
            _scoreTextTmp.text = score.ToString();
            // _timeText.text = time;
        }

        // Public Methods End

        // Lifecycle Methods Begin
        protected void Awake()
        {
            InitHier();
            InitPart();
        }

        private void InitPart()
        {
            // Do initialization here...
        }

        private void Start()
        {
        }

        // Lifecycle Methods End


        // Hier Components Begin        
        private TMP_Text _rankTextTmp;
        private TMP_Text _nameTextTmp;
        private TMP_Text _scoreTextTmp;

        private void InitHier()
        {
            _rankTextTmp = transform.Find("_TextTmp_Rank").GetComponentEx<TMP_Text>();
            _nameTextTmp = transform.Find("_TextTmp_Name").GetComponentEx<TMP_Text>();
            _scoreTextTmp = transform.Find("_TextTmp_Score").GetComponentEx<TMP_Text>();
        }


        // Hier Components End

    }
}
